package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;

import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

import static org.apache.commons.lang3.StringUtils.isBlank;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Reference
    private OrderService orderService;

    @Autowired
    private JedisPool jedisPool;


    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map) throws Exception {
        //页面上的验证码
        String m_code = (String) map.get("validateCode");

        //用户手机号 用来取存储在redis上的验证码
        String telephone = (String) map.get("telephone");
        String r_code = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);

        //验证码校验
        if (isBlank(m_code) || isBlank(r_code) || !m_code.equals(r_code)) {
            //都为空 校验失败
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

        //验证码校验成功
        //设置预约类型
        map.put("orderType", Order.ORDERTYPE_WEIXIN);

        Result result =orderService.order(map);

        //到这里没出错证明预约完成 预约完成发送短信给用户
        if (result.isFlag()) {
            try {
                String[] str = new String[2];
                str[0] = (String) map.get("name");
                str[1] = (String) map.get("orderDate");
                SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone,str);
            } catch (ClientException e) {
                e.printStackTrace();
            }
        }

        return result;

    }

    @RequestMapping("/findById")
    public Result findById(Integer id) throws Exception {

        Result result = orderService.findById(id);

        return result;
    }
}
